package com.northchurchcolumbus.podcast.ncpodcaster;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.apache.commons.net.ftp.FTPClient;

public class FTPUploader implements Uploader
{

    public void upload(File mp3, String directory, String newFileName,
            Map<String, String> credentials, UploaderProgressListener listener, boolean deleteExistingFile) throws Exception
    {
        FTPClient f= new FTPClient();
        f.connect(credentials.get("ftp_server"));
        f.login(credentials.get("ftp_username"), credentials.get("ftp_password"));
        f.changeWorkingDirectory(directory);
        if(deleteExistingFile)
        {
            f.deleteFile(newFileName);
        }
        f.setFileType(FTPClient.BINARY_FILE_TYPE);

        InputStream is = new BufferedInputStream(new FileInputStream(mp3));
        OutputStream os = f.storeFileStream(newFileName);
        byte[] bytes = new byte[1024];
        int bread = -1;
        long totalBytesWritten=0;
        long totalFileBytes=mp3.length();
        while((bread=is.read(bytes))>=0)
        {
            os.write(bytes, 0, bread);
            totalBytesWritten+=bread;
            if(listener!=null)
            {
                listener.updateProgress(totalFileBytes, totalBytesWritten);
            }
        }
        os.close();
        is.close();
       
        
        f.storeFile(newFileName, new FileInputStream(mp3));
        f.logout();
        f.disconnect();
    }
    
}
